package com.mystore.common.utils.file;

import com.mystore.common.consts.ApplicationConst;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class FileUpDownUtils {
    public static void download(String virtualPath, HttpServletResponse response) throws IOException {
        InputStream inputStream=FileUtils.getFileInputStream(virtualPath);
        String fileName=PathUtils.getFileName(virtualPath);
        response.reset();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("application/octet-stream");
        writeStream(response, inputStream);
    }
    public static void loadImage(String virtualPath, HttpServletResponse response) throws IOException {
        InputStream inputStream=FileUtils.getFileInputStream(virtualPath);
        String fileName=PathUtils.getFileName(virtualPath);
        response.reset();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("image/png");
        writeStream(response, inputStream);
        return;
    }

    private static void writeStream(HttpServletResponse response, InputStream inputStream) throws IOException {
        BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
        int len=0;
        byte[] cache=new byte[1024];
        while ((len=inputStream.read(cache))!=-1){
            outputStream.write(cache,0,len);
        }
        outputStream.flush();
    }

    public static List<String> upload(MultipartFile[] multipartFiles, HttpServletRequest request){
        List<String> abPaths=new ArrayList<>();
        if(multipartFiles==null||multipartFiles.length==0)
            return abPaths;
        Arrays.stream(multipartFiles).forEach(multipartFile -> {
            String checkPath="/"+request.getSession().getId();
            File fp=new File(ApplicationConst.DEFAULT_FILE_PATH +checkPath);
            if(!fp.exists())
                fp.mkdir();
            String abPath=checkPath+"/"+new Date().getTime()+multipartFile.getOriginalFilename();
            String path=ApplicationConst.DEFAULT_FILE_PATH+abPath;
            try {
                System.out.println("added one");
                multipartFile.transferTo(new File(path));
                abPaths.add(abPath);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }});

        return abPaths;
    }

}
